#! /usr/bin/env bash

unset ZEEK_DISABLE_ZEEKYGEN

# If running this from btest, unset any of the environment
# variables that alter default script values.
unset ZEEK_DEFAULT_LISTEN_ADDRESS
unset ZEEK_DEFAULT_LISTEN_RETRY
unset ZEEK_DEFAULT_CONNECT_RETRY

dir="$(cd "$(dirname "$0")" && pwd)"
source_dir="$(cd $dir/.. && pwd)"
build_dir=$source_dir/build
conf_file=$build_dir/zeekygen-test.conf
output_dir=$source_dir/doc

if [ -n "$1" ]; then
    output_dir=$1
fi

case $output_dir in
    /*) ;;
    *) output_dir=$(pwd)/$output_dir ;;
esac

cd $build_dir
. zeek-path-dev.sh
export ZEEK_SEED_FILE=$source_dir/testing/btest/random.seed

function run_zeek {
    ZEEK_ALLOW_INIT_ERRORS=1 zeek -X $conf_file zeekygen

    if [ $? -ne 0 ]; then
        echo "Failed running zeek with zeekygen config file $conf_file" >&2
        exit 1
    fi
}

scripts_output_dir=$output_dir/scripts
rm -rf $scripts_output_dir
printf "script\t*\t$scripts_output_dir/" >$conf_file
echo "Generating $scripts_output_dir/"
run_zeek

script_ref_dir=$output_dir/script-reference
mkdir -p $script_ref_dir

function generate_index {
    echo "Generating $script_ref_dir/$2"
    printf "$1\t*\t$script_ref_dir/$2\n" >$conf_file
    run_zeek
}

generate_index "script_index" "autogenerated-script-index.rst"
generate_index "package_index" "autogenerated-package-index.rst"
generate_index "file_analyzer" "autogenerated-file-analyzer-index.rst"
generate_index "proto_analyzer" "autogenerated-protocol-analyzer-index.rst"
generate_index "packet_analyzer" "autogenerated-packet-analyzer-index.rst"

echo

branch="$(git branch --show-current)"

if [[ "$branch" =~ ^release/.* ]]; then
    doc_config_file=$source_dir/doc/conf.py
    cat ${doc_config_file} | sed \
        -e "s#\(zeek_code_version[[:space:]]*=[[:space:]]*\)[^\n]*#\1'$branch'#g" \
        >${doc_config_file}.tmp
    mv ${doc_config_file}.tmp ${doc_config_file}
fi

if [ -n "$(cd $source_dir/doc && git status --porcelain)" ]; then
    echo "*** There are changes in the doc directory that need a review, commit, and push ***"
else
    echo "No changes or further action needed"
fi
